package com.mzd.multipledatasources2.service;

import com.mzd.multipledatasources2.bean.TeachersBean;
import com.mzd.multipledatasources2.bean.UserBean;
import com.mzd.multipledatasources2.dao.test01.TransactionDao1;
import com.mzd.multipledatasources2.dao.test02.TransactionDao2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author Administrator
 */
@Service
public class TransactionService1 {

    @Autowired
    private TransactionDao1 ts1;
    @Autowired
    private TransactionService2 ts2;
    @Autowired
    private TransactionDao2 td2;

    @Transactional(rollbackFor = Exception.class)
    public boolean savetestBean(UserBean t) {
        return ts1.save(t);
    }

    @Transactional(rollbackFor = Exception.class)
    public void savetestBean2(UserBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = ts2.saveTeacher(tb);
        System.out.println("添加老师 = " + b);
        int i = 1 / 0;
        boolean save = ts1.save(t);
        System.out.println("添加学生 = " + save);
    }

    @Transactional(rollbackFor = Exception.class)
    public void savetestBean3(UserBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = ts2.saveTeacher2(tb);
        System.out.println("添加老师 = " + b);
//        int i = 1 / 0; // 有没有这行都添加不进去
        boolean save = ts1.save(t);
        System.out.println("添加学生 = " + save);
    }

    /**
     * 直接注入数据源2的dao层就不收这个事务控制了
     *
     * @param t
     */
    @Transactional(rollbackFor = Exception.class)
    public void savetestBean4(UserBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = td2.save(tb);
        System.out.println("添加老师 = " + b);
        int i = 1 / 0;
        boolean save = ts1.save(t);
        System.out.println("添加学生 = " + save);
    }

}
